import cv2
import numpy as np

# 打开摄像头
cap = cv2.VideoCapture(1)

while True:
    ret, frame = cap.read()
    if not ret:
        break

    # 转灰度图
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # 二值化处理
    _, thresh = cv2.threshold(gray, 150, 255, cv2.THRESH_BINARY_INV)

    # 轮廓查找
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    paper_contour = None
    max_area = 0

    for cnt in contours:
        area = cv2.contourArea(cnt)
        approx = cv2.approxPolyDP(cnt, 0.02 * cv2.arcLength(cnt, True), True)

        # 找面积最大且近似为四边形的轮廓
        if area > 10000 and len(approx) == 4:
            if area > max_area:
                max_area = area
                paper_contour = approx

    if paper_contour is not None:
        # 绘制轮廓
        cv2.drawContours(frame, [paper_contour], -1, (255, 0, 0), 2)

        # 计算中心点
        M = cv2.moments(paper_contour)
        if M["m00"] != 0:
            cx = int(M["m10"] / M["m00"])
            cy = int(M["m01"] / M["m00"])
            # 标记中心点
            cv2.circle(frame, (cx, cy), 5, (0, 255, 0), -1)
            # 显示坐标
            cv2.putText(frame, f"({cx}, {cy})", (cx + 10, cy),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)

    cv2.imshow("A4 Paper Detection", frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
